#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERR_EXIT(m) \
    do { \
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0)

int Myrecv(int fd,char* buff,int len);
void Myread(int fd,char* buff);
void do_service(int sockfd);

int main(int argc, const char *argv[])
{
    int peerfd = socket(PF_INET, SOCK_STREAM, 0);
    if(peerfd == -1)
        ERR_EXIT("socket");

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("192.168.127.132"); //localhost
    /* addr.sin_addr.s_addr = inet_addr("127.2.0.0"); //localhost */
    //addr.sin_addr.s_addr = INADDR_ANY; //localhost
    addr.sin_port = htons(2020);
    socklen_t len = sizeof addr;
    if(connect(peerfd, (struct sockaddr*)&addr, len) == -1)
        ERR_EXIT("Connect");

    char buf[1024];
    memset(buf, 0, sizeof(buf));
    Myread(peerfd, buf );
    printf("%s\n", buf);

    do_service(peerfd);
    return 0;
}



void do_service(int sockfd)
{
    char recvbuf[1024] = {0};
    char sendbuf[1024] = {0};
    while(1)
    {
        fgets(sendbuf, sizeof sendbuf, stdin);
        write(sockfd, sendbuf, strlen(sendbuf));

        //read
        Myread(sockfd,recvbuf);
        int flag=atoi(recvbuf);
        memset(recvbuf, 0, sizeof recvbuf);
        if(flag==0)
        {
            printf("Error,pls check your input!\n");
        }
        else{
            /* Myread(sockfd,recvbuf); */
            /* printf("receive size : %s\n", recvbuf); */
            /* memset(recvbuf, 0, sizeof recvbuf); */
            printf("receive data: ");
            Myread(sockfd,recvbuf);
            printf("%s\n",recvbuf);
            memset(recvbuf, 0, sizeof recvbuf);
        }

        memset(sendbuf, 0, sizeof sendbuf);
    }

}
void Myread(int fd,char* buff)
{
    char len[32];
    Myrecv(fd,len,4);
    int sz=atoi(len);
    /* printf("%d\n",sz); */
    Myrecv(fd,buff,sz);
    /* printf("%s\n",buff); */
    
}

int Myrecv(int fd,char* buff,int len)
{
    int left=len;
    char* p=buff;
    while(left>0){
        int ret=read(fd,p,left);
        if(ret==-1&&errno==EINTR)
            continue;
        else if(ret==-1){
            perror("read");
            return len-left;

        }
        else if(ret==0){
            return len-left;

        }else{
            left-=ret;
            p+=ret;
        }
    }
    return len-left;
}
